package Http;

import sun.net.www.http.HttpClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 构造http请求
 */
public class http1 {
    private Socket socket;
    private int port;
    private String ip;

    public http1( int port, String ip) throws IOException {
        this.port = port;
        this.ip = ip;
        this.socket = new Socket(ip, port);
    }
    public String get(String url) throws IOException {
        StringBuilder request=new StringBuilder();
        //构造首行
        request.append("GET "+url+" HTTP/1.1\n");
        //构造header
        request.append("Host: "+ ip + ":" + port + "\n");
        //构造空行
        request.append("\n");
        //get不需要body
        OutputStream outputStream=socket.getOutputStream();
        outputStream.write(request.toString().getBytes());

        //读取响应
        InputStream inputStream=socket.getInputStream();
        byte[]bytes=new byte[1024];
        int n=inputStream.read(bytes);
        return new String(bytes,0,n,"utf-8");
    }
}
